package org.celery.modules.purchase.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.celery.modules.purchase.enums.PurchaseStatusEnum;
import org.celery.modules.shop.entity.Shop;
import org.celery.modules.shop.service.IShopService;
import org.celery.modules.ticket.entity.Ticket;
import org.celery.modules.ticket.service.ITicketService;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.celery.modules.purchase.entity.Purchase;
import org.celery.modules.purchase.vo.PurchaseVO;
import org.celery.modules.purchase.wrapper.PurchaseWrapper;
import org.celery.modules.purchase.service.IPurchaseService;
import org.springblade.core.boot.ctrl.BladeController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 店铺表 控制器
 *
 * @author Celery
 * @since 2023-07-16
 */
@RestController
@AllArgsConstructor
@RequestMapping("celery-purchase/purchase")
@Api(value = "店铺表", tags = "店铺表接口")
public class PurchaseController extends BladeController {

	private final IPurchaseService purchaseService;
	private final ITicketService ticketService;
	private final IShopService shopService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入purchase")
	public R<PurchaseVO> detail(Purchase purchase) {
		Purchase detail = purchaseService.getOne(Condition.getQueryWrapper(purchase));
		return R.data(PurchaseWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 店铺表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入purchase")
	public R<IPage<PurchaseVO>> list(Purchase purchase, Query query,
									 @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") LocalDateTime createTimeStart,
									 @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") LocalDateTime createTimeEnd,
									 BladeUser user) {
		QueryWrapper<Purchase> queryWrapper = Condition.getQueryWrapper(purchase);
		if(!user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) || (!user.getRoleName().contains("administrator") && !user.getRoleName().contains("s_admin") && !user.getRoleName().contains("caiwu") && !user.getRoleName().contains("fake_boss"))) {
			List<Shop> shopList = shopService.authList(user);
			if (Func.isEmpty(shopList)) {
				return R.data(new Page<>());
			}

			List<String> shopNameList = shopList.stream().map(Shop::getResourceOwner).collect(Collectors.toList());
			queryWrapper.lambda().in(Purchase::getUserName, shopNameList);
		}
		if (Func.isNotEmpty(createTimeStart) && Func.isNotEmpty(createTimeEnd)) {
			queryWrapper.lambda().between(Purchase::getCreateTime, createTimeStart, createTimeEnd);
		}
		IPage<Purchase> pages = purchaseService.page(Condition.getPage(query), queryWrapper);
		return R.data(PurchaseWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 店铺表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入purchase")
	public R<IPage<PurchaseVO>> page(PurchaseVO purchase, Query query) {
		IPage<PurchaseVO> pages = purchaseService.selectPurchasePage(Condition.getPage(query), purchase);
		return R.data(pages);
	}

	/**
	 * 新增 店铺表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入purchase")
	public R save(@Valid @RequestBody Purchase purchase) {
		return R.status(purchaseService.save(purchase));
	}

	/**
	 * 自定义 新增 店铺表
	 */
	@PostMapping("/custom-save")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "新增", notes = "传入purchase")
	public R savePurchaseObject(@Valid @RequestBody Purchase purchase) {
		return R.status(purchaseService.savePurchaseObject(purchase));
	}

	/**
	 * 修改 店铺表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入purchase")
	public R update(@Valid @RequestBody Purchase purchase) {
		return R.status(purchaseService.updateById(purchase));
	}

	/**
	 * 新增或修改 店铺表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入purchase")
	public R submit(@Valid @RequestBody Purchase purchase) {
		Long ticketId = purchase.getTicketId();
		Ticket ticket = ticketService.getById(ticketId);
		if (Func.isEmpty(ticket)) {
			throw new ServiceException("关联订单单号不存在!");
		}
		return R.status(purchaseService.saveOrUpdate(purchase));
	}

	
	/**
	 * 删除 店铺表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(purchaseService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 新增或修改 店铺表
	 */
	@PostMapping("/submit-for-alipay")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "新增或修改", notes = "传入purchase")
	public R submitForAlipay(@Valid @RequestBody Purchase purchase) {
		List<Purchase> list = purchaseService.list(Wrappers.<Purchase>lambdaQuery()
				.eq(Purchase::getTicketId, purchase.getTicketId())
				.isNotNull(Purchase::getPurchaseCode)
				.eq(Purchase::getStatus, PurchaseStatusEnum.UNPAID.getValue())
		);
		Ticket ticket = ticketService.getById(purchase.getTicketId());
		if (Func.isNotEmpty(list)) {
			Purchase item = list.get(0);
			item.setRemark(purchase.getRemark());
			item.setAmount(purchase.getAmount());
			if (Func.isNotEmpty(ticket)) {
				item.setTicketAmount(ticket.getActualPrice());
				item.setUserName(ticket.getUserName());
			}
			return R.status(purchaseService.updateById(item));
		}

		return R.status(false);
	}


	/**
	 * 新增或修改 店铺表
	 */
	@PostMapping("/sync-info")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "新增或修改", notes = "传入purchase")
	public R syncInfo(@Valid @RequestBody Purchase purchase) {
		List<Purchase> list = purchaseService.list(Wrappers.<Purchase>lambdaQuery()
				.eq(Purchase::getTicketId, purchase.getTicketId())
				.eq(Purchase::getPurchaseCode, purchase.getPurchaseCode())
		);

		if (Func.isNotEmpty(list)) {
			Purchase item = list.get(0);
			item.setMailName(purchase.getMailName());
			if (Func.isNotEmpty(purchase.getStatus())) {
				item.setStatus(purchase.getStatus());
			}
			return R.status(purchaseService.updateById(item));
		}

		return R.status(purchaseService.save(purchase));
	}

	/**
	 * 空实现，主要是为了插件拿到mailName
	 */
	@RequestMapping("/get-mailName")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "空实现，主要是为了插件拿到mailName", notes = "无")
	public R<Boolean> getMailName(HttpServletResponse response, @RequestParam String mailName) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
		return R.status(purchaseService.getMailName(mailName));
	}

	/**
	 * 用于检测是否退款，将退款的订单状态改变
	 */
	@RequestMapping("/change-ticket-status")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "用于检测是否退款，将退款的订单状态改变", notes = "无")
	public R<Boolean> changeTickStatus(@RequestParam String mailName, @RequestParam Integer status) {
		return R.status(purchaseService.changeTickStatus(mailName, status));
	}


	@GetMapping("/location-good-list")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "筛选当前用户存在，可以拿到的订单号方便页面跳转", notes = "无")
	public R<String> getPurchaseLocationGoodList() {
		return R.data(purchaseService.getPurchaseLocationGoodList());
	}

	@GetMapping("/statics")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "获取各店铺统计列表", notes = "无")
	public R<List<Map<String, Object>>> statics(@RequestParam(required = false) String shopName,
												@RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
												@RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
												BladeUser user
	) {
		return R.data(purchaseService.staticsList(shopName, startTime, endTime, user));
	}
}
